package com.dubbo.service.impl;

import com.alibaba.fastjson.JSON;
import com.dubbo.common.ResponseUtil;
import com.dubbo.common.check.CheckUtil;
import com.dubbo.common.kuaidinao.LogisticsUtil;
import com.dubbo.common.page.PageResponse;
import com.dubbo.common.page.PageUtils;
import com.dubbo.common.push.JpushClientUtil;
import com.dubbo.common.redis.RedisDao;
import com.dubbo.common.redis.tool.RedisConstant;
import com.dubbo.common.result.ResultInfo;
import com.dubbo.domain.*;
import com.dubbo.domain.info.ResultMessage;
import com.dubbo.domain.other.FileInfo;
import com.dubbo.domain.other.ZeroHourFile;
import com.dubbo.mapper.*;
import com.dubbo.mapper.auth.RoleUserKeyMapper;
import com.dubbo.mapper.other.FileInfoMapper;
import com.dubbo.mapper.other.ZeroHourFileMapper;
import com.dubbo.service.business.my.MyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
/**
 * 我的
 * @author lihongwu
 * 2018年12月15日 下午3:04:14
 */
@Service
@Transactional(readOnly=false,rollbackFor=Exception.class)
public class MyServiceImpl implements MyService {
	
	@Autowired
	private UserWalletKeyMapper userWalletKeyMapper;
	@Autowired
	private WalletMapper walletMapper;
	@Autowired
	private WalletAmountMapper walletAmountMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private FileInfoMapper fileInfoMapper;
	@Autowired
	private UserMessageMapper userMessageMapper;
	@Value("${fastdfsUrl}")
	private String fastdfsUrl;
	@Autowired
	private RoleUserKeyMapper roleUserKeyMapper;
	@Value("${electricId}")
	private String electricId;
	@Value("${traderId}")
	private String traderId;
	@Autowired
	private OptionMapper optionMapper;
	@Autowired
	private ShippingMapper shippingMapper;
	@Autowired
	private PicMapper picMapper;
	@Autowired
	private OptionPicKeyMapper optionPicKeyMapper;
	@Autowired
	private URoleLevelMapper uRoleLevelMapper;
	@Autowired
	private ZeroHourFileMapper zeroHourFileMapper;
	
	@Value("${eBusinessID}")
	private String eBusinessID;
	@Value("${kuaidiniao_appKey}")
	private String kuaidiniaoAppKey;
	@Autowired
	private RedisDao redisDao;
	@Value("${user.prefixkey.redis}")
	private String userTicket;
	@Value("${shiro.session.timeout}")
	private long userSeconds;
	@Autowired
	private MessageMapper messageMapper;
	/**
	 * 我的补助金(只有电工才能访问此接口)
	 *
	 * @author lihongwu
	 * 2018年12月15日 下午3:24:14
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> myInstallSubsidy(User user) {
		//获取用户钱包
		UserWalletKey userWalletKey = new UserWalletKey();
		userWalletKey.setUserid(user.getId());
		userWalletKey = userWalletKeyMapper.selectOne(userWalletKey);
		Wallet wallet = walletMapper.selectByPrimaryKey(userWalletKey.getWalletid());
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, wallet);
	}

	/**
	 * 安装补助金记录(只有电工才能访问此接口)
	 *
	 * @author lihongwu
	 * 2018年12月15日 下午4:07:17
	 * @param user
	 * @param pageStart
	 * @param pageTotal
	 * @return
	 */
	@Override
	public Map<String, Object> installSubsidyDetail(User user, Long pageStart, Long pageTotal) {
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		List<Map<String, Object>> data = walletAmountMapper.installSubsidyDetail(user.getId(), countPageStart, pageTotal);
		Long pageCount = walletAmountMapper.installSubsidyDetailCount(user.getId());
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,new PageResponse(pageStart, pageTotal, pageCount, data));
	}

	/**
	 * 提现记录
	 *
	 * @author lihongwu
	 * 2018年12月15日 下午5:03:24
	 * @param user
	 * @param pageStart
	 * @param pageTotal
	 * @return
	 */
	@Override
	public Map<String, Object> drawithDetail(User user, Long pageStart, Long pageTotal) {
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		List<Map<String, Object>> data = walletAmountMapper.drawithDetail(user.getId(), countPageStart, pageTotal);
		for(Map<String, Object> m:data) {
			m.put("amount", m.get("amount").toString().replace("-", ""));
		}
		Long pageCount = walletAmountMapper.drawithDetailCount(user.getId());
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,new PageResponse(pageStart, pageTotal, pageCount, data));
	}

	/**
	 * 我的电工
	 * @author gujiahua
	 * 2018年12月17日 上午11:09:46
	 * @param user
	 * @param pageStart
	 * @param pageTotal
	 * @param keyWord
	 * @return
	 */
	@Override
	public Map<String, Object> getElectriciansList(User user, Long pageStart, Long pageTotal, String keyWord) {
		//初始化数据
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		Long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		//解决keyWord为空数据库查不到数据
		if(StringUtils.isBlank(keyWord)) {
			keyWord="";
		}
		List<Map<String,Object>> electricians = 
				userMapper.getElectricians(user.getId(),countPageStart, pageTotal, keyWord);
		this.handleListPics(electricians, "avatarUrl");
		Long pageCount = (long) userMapper.getElectriciansCount(user.getId(), keyWord);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,
				new PageResponse(pageStart, pageTotal, pageCount, electricians));
	}


	/**
	 * list图片处理
	 * @author chenluqiang
	 * @date 2018年12月18日 下午4:01:53 
	 * @param code key值
	 * @param list
	 */
	private void handleListPics(List<Map<String,Object>> list,String code) {
		//遍历处理
		if(list!=null&&!list.isEmpty()) {
			for(Map<String,Object> map : list) {
				if(map.get(code)!=null&&StringUtils.isNotBlank(map.get(code).toString())) {
					map.put(code, this.getPic(map.get(code).toString()));
				}
			}
		}
	}
	
	/**
	 * 我的分销商
	 * @author gujiahua
	 * 2018年12月17日 上午11:50:31
	 * @param user
	 * @param pageStart
	 * @param pageTotal
	 * @param keyWord
	 * @return
	 */
	@Override
	public Map<String, Object> getDistributorsList(User user, Long pageStart, Long pageTotal, String keyWord) {
		//初始化数据
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		Long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		if(StringUtils.isBlank(keyWord)) {
			keyWord="";
		}
		List<Map<String,Object>> distributors = 
				userMapper.getDistributors(user.getId(), countPageStart, pageTotal, keyWord);
		this.handleListPics(distributors, "avatarUrl");
		Long pageCount = (long) userMapper.getDistributorsCount(user.getId(), keyWord);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, 
				new PageResponse(pageStart, pageTotal, pageCount, distributors));
	}

	/**
	 * 获取推荐二维码 (代理商，分销商，电工都通过这个接口获取推荐二维码)
	 *
	 * @author lihongwu
	 * 2018年12月15日 下午5:31:04
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> getCode(User user) {
		user = userMapper.selectByPrimaryKey(user.getId());
		Map<String,Object> map = new HashMap<>();
		map.put("codeA", getPic(user.getCodea()));
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, map);
	}

	/**
	 * 获取个人信息
	 * @author gujiahua
	 * 2018年12月18日 上午11:07:36
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> getInformation(User user) {
		Map<String, Object> informations = userMapper.getUserInformations(user.getId());
		if(informations!=null) {
			Object pic = informations.get("avatarUrl");
			if(pic!=null && StringUtils.isNotBlank(pic.toString())){
				informations.put("avatarUrl",getPic(pic.toString()) );
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, informations);
		
	}

	
	
	/**
	 * 图片地址校验
	 * @author gujiahua
	 * 2018年12月18日 上午11:41:57
	 * @param string
	 * @return
	 */
	private String getPic(String pic) {
		if(!CheckUtil.checkUrl(pic)){
			pic = fastdfsUrl+pic;
		}
		return pic;
	}

	/**
	 * 修改头像
	 * @author gujiahua
	 * 2018年12月18日 上午11:28:59
	 * @param user
	 * @param picId
	 * @return
	 */
	@Override
	public Map<String, Object> updateHeaderImg(User user, String picId) {
		user = userMapper.selectByPrimaryKey(user.getId());
		if(picId==null || !StringUtils.isNotBlank(picId)){
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL);
		}
		//从文件表获取文件路径
		FileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(picId);
		if(fileInfo!=null){
			user.setAvatarurl(fileInfo.getUrl());
			
			//删除临时表
			ZeroHourFile zeroHourFile = new ZeroHourFile();
			zeroHourFile.setFileInfoId(fileInfo.getId());
			zeroHourFileMapper.delete(zeroHourFile);
		}
		
		user.setUpdateTime(new Date());
		userMapper.updateByPrimaryKeySelective(user);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 获取用户消息
	 * @author gujiahua
	 * 2018年12月18日 上午11:55:12
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> getUserMessageList(User user, Long pageStart, Long pageTotal) {
		pageStart = PageUtils.initialPageStart(pageStart);
		pageTotal = PageUtils.packagePageTotal(pageTotal, 5, 10);
		Long countPageStart = PageUtils.countPageStart(pageStart, pageTotal);
		List<Map<String,Object>> messageList = 
				userMapper.getMessageList(user.getId(),countPageStart,pageTotal);
		UserMessage userMessage = new UserMessage();
		userMessage.setUserid(user.getId());
		Long pageCount = (long) userMessageMapper.selectCount(userMessage);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,
				new PageResponse(pageStart, pageTotal, pageCount, messageList));
	}

	/**
	 * 扫码获取到userId之后调用的接口
		若普通用户扫代理商和分销商，直接成为电工
		若分销商和代理商扫普通用户或代理商扫电工，则页面显示邀请按钮
	 *
	 * @author lihongwu
	 * 2018年12月24日 上午11:38:58
	 * @param request
	 * @param codeUserId
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> sweepCode(User user, String codeUserId) {
		User codeUser = userMapper.selectByPrimaryKey(codeUserId);
		//校验参数
		Map<String,Object> check = checkSweepCodeParam(codeUser,user);
		if(check!=null) {
			return check;
		}
		
		int codeUserType = codeUser.getType(); //二维码所属用户的用户类型    0=普通用户 1=代理商 2=分销商(商家) 3=电工 
		int userType = user.getType();  //扫二维码用户的用户类型    0=普通用户 1=代理商 2=分销商(商家) 3=电工
		
		//状态   0=扫码用户直接成为电工   1=扫码用户是分销商，邀请普通用户成为电工  2=扫码用户是代理商，邀请普通用户成为电工或分销商   
		//3=扫码用户是代理商,邀请电工成为分销商
		int status = 0;
	
		//返回结果
		Map<String,Object> result = new HashMap<>();
		
		
		//若扫码用户是普通用户且二维码所属用户为代理商或分销商
		if(userType==0 && (codeUserType==1 || codeUserType==2)) {
			user.setUserParentId(codeUserId);
			user.setType(3);  //将用户改为电工角色类型
			userMapper.updateByPrimaryKeySelective(user);
			roleUserKeyMapper.updateUserRole(user.getId(), electricId); //将用户与电工角色关联
			//设置层级关系
			URoleLevel uRoleLevel = new URoleLevel();
			uRoleLevel.setUserid(user.getId());
			uRoleLevel.setElectricid(user.getId());
			if(codeUserType==1) {
				uRoleLevel.setAgentid(codeUserId);
			}else if(codeUserType==2) {
				uRoleLevel.setTraderid(codeUserId);
				uRoleLevel.setAgentid(codeUser.getUserParentId());
			}
			uRoleLevelMapper.insertSelective(uRoleLevel);
			
			//添加系统消息
			//被邀请方
			Message message = new Message();
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(user.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent(ResultMessage.UPGRADE_ELECTRIC);
			message.setType(0);//0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
			//邀请方
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(codeUser.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent("您邀请的"+user.getNickName()+"成功注册为狮盾会员电工");
			message.setType(0);//0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
//			消息推送
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(user!=null&&StringUtils.isNoneBlank(user.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(user.getRegistrationId(), "成为电工", "成为电工", "成功注册为狮盾会员电工", "", "", "", new HashMap<>());
			}
		}
		//若扫码用户是代理商且二维码所属用户为普通用户
		if(userType==1 && codeUserType==0) {
			status = 2;
		}
		//若扫码用户是代理商且二维码所属用户为电工
		if(userType==1 && codeUserType==3) {
			status = 3;
		}
		//若扫码用户是分销商且二维码所属用户为普通用户
		if(userType==2 && codeUserType==0) {
			  status = 1;
		}
		
		result.put("status", status);
		result.put("codeUserName", codeUser.getNickName());   //二维码所属人名字
		result.put("codeUserPhone", codeUser.getPhone());	//二维码所属人手机号
		result.put("codeUserArea", codeUser.getProvince()+codeUser.getCity()+codeUser.getCountry()); //二维码所属人地区
		result.put("codeUserType", codeUser.getType());	//二维码所属人账号类型    0=普通用户 1=代理商 2=分销商(商家) 3=电工
		result.put("headUrl", getPic(codeUser.getAvatarurl())); //二维码所属人头像
		
		String key = saveUserByRedis(redisDao, user);
		result.put(ResultInfo.USERTOKEN,key);
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
	}

	/**
	 * 校验扫码之后调用的接口的参数
	 *
	 * @author lihongwu
	 * 2018年12月24日 下午2:30:25
	 * @param codeUser
	 * @return
	 */
	private Map<String, Object> checkSweepCodeParam(User codeUser,User user) {
		if(codeUser==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.INVALID_CODE,"code is invalid");
		}
		
		int codeUserType = codeUser.getType(); //二维码所属用户的用户类型    0=普通用户 1=代理商 2=分销商(商家) 3=电工 
		int userType = user.getType();  //扫二维码用户的用户类型    0=普通用户 1=代理商 2=分销商(商家) 3=电工
		
		//若扫二维码用户和二维码所属用户是同级
		if((userType==codeUserType)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.IS_EQUAL_LEVEL,"code is invalid");
		}
		//若扫码用户是普通用户且二维码所属用户是电工
		if(userType==0 && codeUserType==3) {
			return ResponseUtil.ajaxCheckError(ResultMessage.NOT_COMMON_INVALID_ELECT,"code is invalid");
		}
		//若扫码用户是代理商且二维码所属用户是分销商
		if(userType==1 && codeUserType==2) {
			return ResponseUtil.ajaxCheckError(ResultMessage.AGENT_NOT_INVALID_TRADER,"code is invalid");
		}
		//若扫码用户是分销商且二维码所属用户是电工或代理商
		if(userType==2 && (codeUserType==3 || codeUserType==1)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.TRADER_NOT_INVALID_ELECT_OR_AGENT,"code is invalid");
		}
		//若扫码用户是电工
		if(userType==3) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ELECT_NOT_INVALID,"code is invalid");
		}
		return null;
	}

	/**
	 * sweepCode的后续接口 , 点击邀请类型按钮之后访问   例如：代理商邀请普通用户，有电工和分销商两个按钮，点击按钮后访问该接口
	 *
	 * @author lihongwu
	 * 2018年12月24日 下午5:08:37
	 * @param request
	 * @param codeUserId
	 * @param type  1=邀请成为电工,2=邀请成为分销商
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> sweepCodeAfter(User user, String codeUserId, Integer type) {
		//校验数据
		if(type==null || type<1 || type>2) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "type is error");
		}
		User codeUser = userMapper.selectByPrimaryKey(codeUserId);
		if(codeUser==null) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR, "codeUserId is error");
		}
		
		//邀请成为电工
		if(type==1) {
			//若邀请方不是分销商或代理商
			if(user.getType()!=1 && user.getType()!=2) {
				return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR,"user type is error");
			}
			//若被邀请方不是普通用户
			if(codeUser.getType()!=0) {
				return ResponseUtil.ajaxCheckError(ResultMessage.USER_IS_ELECTRIC);
			}
			codeUser.setUserParentId(user.getId());
			codeUser.setType(3);  //将用户改为电工角色类型
			userMapper.updateByPrimaryKeySelective(codeUser);
			roleUserKeyMapper.updateUserRole(codeUser.getId(), electricId); //将用户与电工角色关联
			//设置层级关系
			URoleLevel uRoleLevel = new URoleLevel();
			uRoleLevel.setUserid(codeUserId);
			uRoleLevel.setElectricid(codeUserId);
			if(user.getType()==1) {
				uRoleLevel.setAgentid(user.getId());
			}else if(user.getType()==2) {
				uRoleLevel.setTraderid(user.getId());
				uRoleLevel.setAgentid(user.getUserParentId());
			}
			uRoleLevelMapper.insertSelective(uRoleLevel);
			//添加系统消息
			//邀请方
			Message message = new Message();
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(user.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent("您邀请的"+codeUser.getNickName()+"成功注册为狮盾会员电工");
			message.setType(0);//0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
			//被邀请方
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(codeUser.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent(ResultMessage.UPGRADE_ELECTRIC);
			message.setType(0);//0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
			
//			消息推送
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(codeUser!=null&&StringUtils.isNoneBlank(codeUser.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(codeUser.getRegistrationId(), "成为电工", "成为电工", "成功注册为狮盾会员电工", "", "", "", new HashMap<>());
			}
		}else if(type==2) {
			//若邀请方不是代理商
			if(user.getType()!=1) {
				return ResponseUtil.ajaxCheckError(ResultMessage.SYSTEM_ERROR,"user type is error");
			}
			//若被邀请方不是普通用户和电工
			if(codeUser.getType()!=0 && codeUser.getType()!=3) {
				return ResponseUtil.ajaxCheckError(ResultMessage.USER_IS_TRADER);
			}
			
			//被邀请方是普通用户
			if(codeUser.getType()==0) {
				//设置层级关系
				URoleLevel uRoleLevel = new URoleLevel();
				uRoleLevel.setUserid(codeUserId);
				uRoleLevel.setTraderid(codeUserId);
				uRoleLevel.setAgentid(user.getId());
				uRoleLevelMapper.insertSelective(uRoleLevel);
			}else { //被邀请方是电工
				URoleLevel uRoleLevel = uRoleLevelMapper.selectByPrimaryKey(codeUserId);
				uRoleLevel.setElectricid("");
				uRoleLevel.setTraderid(codeUserId);
				uRoleLevel.setAgentid(user.getId());
				uRoleLevelMapper.updateByPrimaryKeySelective(uRoleLevel);
			}
			
			codeUser.setUserParentId(user.getId());
			codeUser.setType(2);  //将用户改为分销商角色类型
			userMapper.updateByPrimaryKeySelective(codeUser);
			roleUserKeyMapper.updateUserRole(codeUser.getId(), traderId); //将用户与分销商角色关联
			//添加系统消息
			
			//邀请方
			Message message = new Message();
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(user.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent("您邀请的"+codeUser.getNickName()+"成功注册为狮盾分销商");
			message.setType(0);  //0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
			//被邀请方
			message.setId(UUID.randomUUID().toString().replace("-", ""));
			message.setUserid(codeUser.getId());
			message.setTitle(ResultMessage.SYSTEM_MESSAGE);
			message.setContent(ResultMessage.UPGRADE_TRADER);
			message.setType(0); //0等于系统消息
			message.setIsRead(0); //未读状态
			message.setCreateTime(new Date());
			message.setUpdateTime(new Date());
			messageMapper.insertSelective(message);
			
//			消息推送
			JpushClientUtil.initJPushClient(ResultMessage.JGTSKEY, ResultMessage.JGTSECRET);
			if(codeUser!=null&&StringUtils.isNoneBlank(codeUser.getRegistrationId())) {
				JpushClientUtil.sendToRegistrationId(codeUser.getRegistrationId(), "成为分销商", "成为分销商", "成功注册为狮盾分销商", "", "", "", new HashMap<>());
			}
		}
		
		//返回结果
		Map<String,Object> result = new HashMap<>();
		result.put("codeUserName", codeUser.getNickName());   //二维码所属人名字
		result.put("codeUserPhone", codeUser.getPhone());	//二维码所属人手机号
		result.put("codeUserArea", codeUser.getProvince()+codeUser.getCity()+codeUser.getCountry()); //二维码所属人地区
		result.put("codeUserType", codeUser.getType());	//二维码所属人账号类型     2=分销商(商家) 3=电工
		result.put("headUrl", getPic(codeUser.getAvatarurl()));  //二维码所属人头像
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, result);
	}

	/**
	 * 提交反馈
	 * @author wujunyuan
	 * @date 2018年12月28日  上午10:14:54
	 * @param user
	 * @param picIds 图片数组
	 * @param content 意见内容
	 * @return
	 */
	@Override
	public Map<String, Object> option(User user, String picIds, String content) {
		//校验参数
		if(StringUtils.isBlank(content)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_ERROR,"content error~");
		}
		//添加数据option表
		Option option = new Option();
		option.setId(UUID.randomUUID().toString().replace("-", ""));
		option.setReplyname(user.getId());
		option.setReplytime(new Date());
		option.setContent(content);
		//处理状态 0=待处理 1=已处理
		option.setStatus(0);
		option.setCreateTime(new Date());
		option.setUpdateTime(new Date());
		//插入数据到意见反馈表
		optionMapper.insertSelective(option);
		if(StringUtils.isNotBlank(picIds)) {
		//切割图片id
		List<String> pids = JSON.parseArray(picIds, String.class);
		
		for (String pid : pids) {
			FileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(pid);
			if(fileInfo!=null) {
				//保存图片
				Pic pic = new Pic();
				pic.setTitle("意见反馈照片");
				pic.setUrl(fileInfo.getPath());
				pic.setCreateTime(new Date());
				pic.setUpdateTime(new Date());
				picMapper.insertSelective(pic);
				
				//删除临时文件
				ZeroHourFile zeroHourFile = new ZeroHourFile();
				zeroHourFile.setFileInfoId(fileInfo.getId());
				zeroHourFileMapper.delete(zeroHourFile);
				
				//保存图片关联
				OptionPicKey optionPicKey = new OptionPicKey();
				optionPicKey.setOptionid(option.getId());
				optionPicKey.setPicid(pic.getId());
				optionPicKeyMapper.insertSelective(optionPicKey);
				}
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 根据电工id 获取 电工信息
	 * @author chenluqiang
	 * @date 2019年1月2日 下午4:51:16 
	 * @param user
	 * @param userId
	 * @return
	 */
	@Override
	public Map<String, Object> getUserMsg(User user, String userId) {
		if(StringUtils.isBlank(userId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PAYTYPE_ERROR,"userId is null~");
		}
		
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,userMapper.getUserMsgByUserId(userId));
	}

	/**
	 * 联系客服
	 * @author wujunyuan
	 * @date 2019年1月3日 上午11:22:04
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> getServicePhone(User user) {
		//获取管理员id
		String sysUserId = user.getSysuserid();
		//根据sysUserId获取客服电话
		Map<String,Object> result = userMapper.getServicePhone(sysUserId);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,result);
	}
	
	/**
	 * 查看订单物流
	 * @author chenluqiang
	 * @date 2019年1月3日 下午4:50:02 
	 * @param request
	 * @param orderId 订单id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getKuaidi(User user, String orderId) throws Exception {
		//数据校验
		if(StringUtils.isBlank(orderId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.ORDERID_ISNULL);
		}
		//获取物流信息
		Map<String,Object> map = shippingMapper.getShippingCodeByOrderId(orderId);
		
		if(map==null||map.isEmpty()||
				map.get("shippingCode")==null||StringUtils.isBlank(map.get("shippingCode").toString())) {
			return ResponseUtil.ajaxCheckError(ResultMessage.SHIPPING_ISNULL);
		}
		
		Map<String,Object> result = LogisticsUtil.getLogisticsResult(
								map.get("shippingCode").toString(),eBusinessID,kuaidiniaoAppKey);
		//设置快递名称
		result.put("shippingName",map.get("shippingName"));
		
		return result;
	}

	/**
	 * 更新店名
	 * @author wujunyuan
	 * @date 2019年1月4日 上午9:56:16
	 * @param user
	 * @param shopName
	 * @return
	 */
	@Override
	public Map<String, Object> editShopName(User user, String shopName,String shopAddress) {
		user = userMapper.selectByPrimaryKey(user.getId());
		if(StringUtils.isBlank(shopName)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"shopName is error~");
		}
		if(shopName.length()>100) {
			return ResponseUtil.ajaxCheckError(ResultMessage.LENGTH_SO_LONG,"shopName is error~");
		}
		
		user.setShopname(shopName);
		user.setShopaddress(shopAddress);
		userMapper.updateByPrimaryKey(user);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 将用户数据保存到redis中并将redis中的key返回
	 */
	@Override
	public String saveUserByRedis(RedisDao redisDao, User user) {
		String ownerJson = JSON.toJSONString(user);
		String uuidKey = UUID.randomUUID().toString();
		String key = RedisConstant.getKey(userTicket, uuidKey);
		redisDao.set(key, ownerJson, userSeconds);
		return key;
	}

	/**
	 * 获取上级电话
	 *
	 * @author lihongwu
	 * 2019年1月18日 下午4:59:21
	 * @param user
	 * @return
	 */
	@Override
	public Map<String, Object> superiorPhone(User user) {
		if(user.getType()!=1) {
			User parentUser = userMapper.selectByPrimaryKey(user.getUserParentId());
			return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,parentUser.getPhone());
		}else{
			Map<String, Object> servicePhone = userMapper.getServicePhone(user.getSysuserid());
			return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,servicePhone.get("servicephone"));
		}
		
	}

	/**
	 * 绑定微信(存openId,wxName)
	 *
	 * @author lihongwu
	 * 2019年2月22日 上午11:07:19
	 * @param request
	 * @param openId
	 * @param wxName 微信昵称
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> bindWx(User user, String openId, String wxName) {
		if(StringUtils.isBlank(openId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"openId");
		}
		if(StringUtils.isBlank(wxName)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"wxName");
		}
		String userId = user.getId();
		//检测数据库是否存在user是绑定了这个微信openId的,有则去除信息
		user = new User();
		user.setOpenId(openId);
		List<User> select = userMapper.select(user);
		if(select!=null &&select.size()!=0) {
			for(User u:select) {
				u.setOpenId("");
				u.setWxName("");
				userMapper.updateByPrimaryKeySelective(u);
			}
		}
		
		//绑定微信
		user = new User();
		user.setId(userId);
		user.setOpenId(openId);
		user.setWxName(wxName);
		userMapper.updateByPrimaryKeySelective(user);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 获取账号绑定的微信号信息
	 *
	 * @author lihongwu
	 * 2019年2月22日 上午11:14:47
	 * @param request
	 * @return
	 */
	@Override
	public Map<String, Object> getBindWx(User user) {
		
		user = userMapper.selectByPrimaryKey(user.getId());
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("openId", user.getOpenId());
		map.put("wxName", user.getWxName()==null?"":user.getWxName());
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, map);
	}

	/**
	 * 获取用户未读消息数量
	 *
	 * @author lihongwu
	 * 2019年2月28日 上午9:47:41
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getUserNoReadMessageCount(User user) {
		Long userNoReadMessageCount = messageMapper.getUserNoReadMessageCount(user.getId());
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK, userNoReadMessageCount);
	}

	/**
	 * 用户读消息(将用户消息全部设置成已读)
	 *
	 * @author lihongwu
	 * 2019年2月28日 上午9:47:41
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> readMessage(User user) {
		messageMapper.readMessage(user.getId());
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}

	/**
	 * 设置用户极光推送所需的设备注册id
	 *
	 * @author lihongwu
	 * 2019年3月1日 上午11:56:45
	 * @param request
	 * @param registrationId
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> setRegistrationId(User user, String registrationId) {
		user = userMapper.selectByPrimaryKey(user.getId());
		user.setRegistrationId(registrationId);
		userMapper.updateByPrimaryKeySelective(user);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 保存用户信息
	 * @author chenluqiang
	 * @date 2019年4月1日 下午3:09:22 
	 *	@param user1
	 *	@param picId
	 *	@param shopName
	 *	@param shopAddress
	 *	@return
	 */
	@Override
	public Map<String, Object> save(User user, String picId, String shopName, String shopAddress) {
		user.setAvatarurl(null);
		if(picId!=null&&StringUtils.isNotBlank(picId)){
			//从文件表获取文件路径
			FileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(picId);
			if(fileInfo!=null){
				user.setAvatarurl(fileInfo.getUrl());
				//删除临时表
				ZeroHourFile zeroHourFile = new ZeroHourFile();
				zeroHourFile.setFileInfoId(fileInfo.getId());
				zeroHourFileMapper.delete(zeroHourFile);
			}
		}
		//设置店名
		if(StringUtils.isBlank(shopName)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"shopName is error~");
		}
		if(shopName.length()>100) {
			return ResponseUtil.ajaxCheckError(ResultMessage.LENGTH_SO_LONG,"shopName is error~");
		}
		//设置店铺地址
		if(StringUtils.isBlank(shopAddress)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"shopAddress is error~");
		}
		if(shopAddress.length()>150) {
			return ResponseUtil.ajaxCheckError(ResultMessage.LENGTH_SO_LONG,"shopAddress is error~");
		}
		user.setShopname(shopName);
		user.setShopaddress(shopAddress);
		user.setUpdateTime(new Date());
		userMapper.updateByPrimaryKeySelective(user);
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK);
	}
	
	/**
	 * 根据用户id获取用户信息
	 * @author chenluqiang
	 * @date 2019年4月1日 下午3:24:10 
	 *	@param userId
	 *	@return
	 */
	@Override
	public Map<String, Object> getInfoById(String userId) {
		if(StringUtils.isBlank(userId)) {
			return ResponseUtil.ajaxCheckError(ResultMessage.PARAMETER_NULL,"userId is null！");
		}
		if(userId.length()>100) {
			return ResponseUtil.ajaxCheckError(ResultMessage.LENGTH_SO_LONG,"userId is error！");
		}
		Map<String, Object> map = userMapper.getInfoById(userId);
		if(map!=null&&!map.isEmpty()) {
			Object pic = map.get("avatarUrl");
			if(pic!=null && StringUtils.isNotBlank(pic.toString())){
				map.put("avatarUrl",getPic(pic.toString()) );
			}
		}
		return ResponseUtil.ajaxCheckSuccess(ResultMessage.OK,map);
	}
}
